import axios from 'axios'

// 拦截器：蒙版Loading/token/修改配置

class DGRequest {
  // request 实例 => axios的实例
  constructor(config) {
    this.instance = axios.create(config)

    // 每个instance实例都添加拦截器
    this.instance.interceptors.request.use(
      (config) => {
        // Loading/token
        console.log('开始发起请求 config: ', config)
        return config
      },
      (err) => {
        console.log('发起请求失败 err: ', err)
        return err
      }
    )

    this.instance.interceptors.response.use(
      (res) => {
        console.log('请求响应成功 res: ', res)
        return res.data
      },
      (err) => {
        console.log('请求响应失败 err: ', err)
        return err
      }
    )

    // 实例的拦截器
    if (config.interceptors) {
      this.instance.interceptors.request.use(
        config.interceptors.requestSuccessFn,
        config.interceptors.requestFailureFn
      )
      this.instance.interceptors.response.use(
        config.interceptors.responseSuccessFn,
        config.interceptors.responseFailureFn
      )
    }
  }

  // 封装网络请求方法
  request(config) {
    if (config.interceptors && config.interceptors.requestSuccessFn) {
      config = config.interceptors.requestSuccessFn(config)
    }
    // return this.instance.request(config)
    return new Promise((resolve, reject) => {
      this.instance
        .request(config)
        .then((res) => {
          if (config.interceptors && config.interceptors.responseSuccessFn) {
            res = config.interceptors.responseSuccessFn(res)
          }
          resolve(res)
        })
        .catch((err) => {
          if (config.interceptors && config.interceptors.responseFailureFn) {
            err = config.interceptors.responseFailureFn(err)
          }
          reject(err)
        })
    })
  }

  get(config) {
    return this.request({ ...config, method: 'GET' })
  }

  post(config) {
    return this.request({ ...config, method: 'POST' })
  }

  delete(config) {
    return this.request({ ...config, method: 'DELETE' })
  }

  patch(config) {
    return this.request({ ...config, method: 'PATCH' })
  }
}

export default DGRequest
